#!/bin/sh 

. %OPTWARE_TARGET_PREFIX%/etc/torrent.conf

SLEEP=60
DEBUG=
UMASK=033
#
##
##############################################

###
## constants
EXIT_NO=0
EXIT_BTGET_NOT_RUNNING=2
EXIT_COMPLETE=3
EXIT_NO_DOWNLOAD=4
##
###

##########################
## Support functions
warning ()
{
    logger -t torrent_watchdog -p warning $*
}

notice ()
{
    logger -t torrent_watchdog -p notice $*
}

debug ()
{
    if [ -n "$DEBUG"  ]; then
        echo $*
    fi
}

##########################
#
# Checks
#

# check the configuration items
if [ ! -d $SOURCE ]; then
    warning "$SOURCE does not exist."
    exit 1
fi

if [ ! -d $TARGET ]; then
    warning "$TARGET does not exist."
    exit 1
fi

if [ ! -d $WORK ]; then
    warning "$WORK does not exist."
    exit 1
fi

if [  -n "$DEBUG"  ]; then
    echo "SOURCE: $SOURCE"
    echo "WORK: $WORK"
    echo "TARGET: $TARGET"
    echo "USER: $USER"
fi

if [ -f $WORK/.watchdog ]; then
    exit 0
fi

touch $WORK/.watchdog
_exit ()
{
    rm $WORK/.watchdog
}
trap _exit EXIT

write_info ()
{
    debug "write_info Writing: ${TORRENT%/*}/.info"
    echo "STARTTIME=\"${STARTTIME}\"
ENDTIME=\"${ENDTIME}\"
TRIES=${TRIES}
PROGRESS=\"${PROGRESS}\"
SCRAPE=\"${SCRAPE}\"
PID=${PID}
TORRENTNAME=\"${TORRENTNAME}\"" > "${TORRENT%/*}/.info"
}



move_to_target ()
{
    debug "Move to target"
    DIRNAME="${TORRENT%/*}"
    DEST="${TARGET}/${DIRNAME##*/}"

    mkdir -p "${DEST}"
    chmod 777 "${DEST}"
    chgrp ${GROUP} "${DEST}"
    chown ${USER} "${DEST}"
    
    cd "${TORRENT%/*}"
    
    chgrp ${GROUP} *
    chown ${USER} *
    chmod ug+rw *

    # Auto purge old logs
    [ -e current.log ] && rm current.log
    [ -e current_error.log ] && rm current_error.log
    
    notice "Moving files to: ${DEST}"
    mv * .info .libbtrc "${DEST}"
    chmod 775 "${DEST}"

    STATUS="Ok"
}

cleanup_work ()
{
    debug "Clean up"
    # cleanup
    debug "Removing work dir: ${TORRENT%/*}"
    rm -rf "${TORRENT%/*}"
}

# Seed recently completed torrent
auto_seed_completed()
{
    if [ "${AUTOSEED}" = "YES" ]; then
	DIRNAME="${TORRENT%/*}"
	DEST="${TARGET}/${DIRNAME##*/}"
	NEWNAME="${DEST}/${TORRENT##*/}"
	notice "Auto seeding ${NEWNAME}.seeding"
	mv "${NEWNAME}" "${NEWNAME}.seeding"
	TORRENT="${NEWNAME}.seeding"
	respawn_torrent
    fi
}

send_report ()
{
    debug "Mail from: $MAILFROM"
    debug "Mail to: $MAILTO"

    if [  -n "${MAILFROM}" -a -n "${MAILTO}" ]; then
	echo "From: <${MAILFROM}>
To: <${MAILTO}>
Subject: ${TORRENTNAME} torrent finished ($STATUS)
------------------
Name          : ${TORRENTNAME}
Torrent       : ${TORRENT}
Started       : ${STARTTIME}
Completed     : ${ENDTIME}
Stored in     : ${TARGET}
Status        : ${STATUS}
"  | ${MAILER:-mini_sendmail} ${MAILOPT}${MAILFROM} ${MAILTO}
        notice "Mail sent to : ${MAILTO}"
    fi
}


# Update progress
update_progress ()
{
    DIRNAME="${TORRENT%/*}"
    debug "update_progress DIRNAME: $DIRNAME"
    DUMMY=`tail -10 "${DIRNAME}/current.log" |tr '\r' '\n'| grep " Download " | tail -1`
    debug "update_progress DUMMY: $DUMMY"
    PROGRESS=$DUMMY

    write_info
}

check_tracker_error ()
{
    [ -f "${TORRENT%/*}/current.log" ] || return

    tail -10 "${TORRENT%/*}/current.log" | grep -q "Error from tracker"  2>/dev/null
if [ $? -eq 0 ]; then   
    debug "Error from tracker"
    warning "Error from tracker"
    . "${TORRENT%/*}/.info"
    kill -TERM $PID
    sleep 2
    PID=""
    mv "${TORRENT}" "${TORRENT}.suspended"
    notice "Torrent ${TORRENT}suspended"
    PROGRESS="Error from tracker"
    write_info
    
    exit 1
fi
}



# Torrent (died) and now is the time to start it over
respawn_torrent()
{
    warning "Respawning torrent ${TORRENT}"
    if [ -f "${TORRENT%.seeding}.seeding" ]; then
        SEED="-s"
    else
        SEED=""
    fi

    cd "${TORRENT%/*}"
    nice nohup btget ${SEED} -t ${LOG_TIME} "${TORRENT}" 2>> current_error.log >> current.log &

    PID=$!
    [ -z "${STARTTIME}" ]  && STARTTIME="`date +"${DATE_FORMAT}"`" 
    PROGRESS="respawned"
    TRIES=$(($TRIES+1))
    write_info 

}


# Torrent exists and runs 
check_if_complete()
{

    debug "check_if_complete  TORRENT:${TORRENT}"
    [ -f "${TORRENT%.seeding}.seeding" ] &&  return


# Kill btget when torrent is complete
   tail -20 "${TORRENT%/*}/current.log" | grep -q "100%" 
   if [ $? -eq 0 ]; then
       . "${TORRENT%/*}/.info"
       kill -TERM $PID
       PID=""
       PROGRESS="completed"
       ENDTIME=`date +"${DATE_FORMAT}"`
       write_info
       move_to_target
       cleanup_work
       send_report
       auto_seed_completed 
   fi
}

##############################################################
# MAIN PROGRAM
#

if [ -f "${WORK}/.paused" ]; then
    notice "Torrents paused"
    debug "Torrents paused"
    exit 3
fi

ACTIVE_TORRENTS=0
# We will check all torrents for running state
for TORRENT in ${WORK}/*/*.torrent ${TARGET}/*/*.torrent.seeding ; do
    INFO="${TORRENT%/*}/.info"
    if [ -f "${INFO}" ]; then
	. "${INFO}"
	if  `grep -q btget /proc/${PID}/cmdline 2> /dev/null` ; then
	    update_progress
	    check_if_complete
	    check_tracker_error
	else # Not a valid PID
		respawn_torrent
        fi   
    else
    	debug "${INFO} not found!"
    fi
    ACTIVE_TORRENTS=$((${ACTIVE_TORRENTS}+1))
done

# Check if any torrent file exists in run env.
TORRENT=`ls -1 $WORK/*/*.torrent 2>/dev/null | head -n 1`

# Start up new  torrent if work is empty
if [ -z "$TORRENT" ]; then
    max_active_torrents=$((${BTLIB_MAXPORT}-${BTLIB_MINPORT}+1))
    if [ ${ACTIVE_TORRENTS} = ${max_active_torrents} ]; then
	notice "Max active torrents (${max_active_torrents}) reached."
	exit 4
    fi
    # check if there is a torrent to process
    FILE=`ls -1 $SOURCE/*.torrent 2>/dev/null | head -n 1`
    if [ -z "$FILE" ]; then
        notice "No torrents to process"
        debug "Nothing to do"
        exit 2
    fi

    TORRENTNAME="${FILE%%.torrent*}"
    TORRENTNAME="${TORRENTNAME##*/}"

    
    mkdir -p "$WORK/$TORRENTNAME"
    chmod 777 "$WORK/$TORRENTNAME"
    
    debug "Moving [$FILE] to [$WORK/$TORRENTNAME]"
    mv "$FILE" "$WORK/$TORRENTNAME"
    
    TORRENT="$WORK/$TORRENTNAME/$TORRENTNAME.torrent"
    debug "Torrent: $TORRENT"

    STARTTIME=`date +"${DATE_FORMAT}"`
    DONE=0

    cd "$WORK/$TORRENTNAME"
    nohup nice btget -t ${LOG_TIME} "${TORRENT}" 2>>current_error.log >>current.log &
    sleep 2
    
    PID=$!
    notice "Starting torrent $TORRENT $PID"
    
    PROGRESS="started" 
    TRIES=0
    ENDTIME=
    SCRAPE=
    write_info

    exit 0
fi







